import React, {Component} from 'react';
import Taro from '@tarojs/taro';
import {Picker, Text, View} from '@tarojs/components'
import {AtDrawer, AtIcon, AtInput, AtList, AtListItem} from 'taro-ui'
import {http} from '../../utils/http'
import {ReverseItem} from '../../utils/server.interface'
import {APPONINTMENT_MY, ORDER_REFUND, TARO_ENV} from '../../constants/api'
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import {vcmonitor} from "../../utils/tools";
import './list.scss'

export default class List extends Component {
  state: {
    appointList: ReverseItem[]
    tabIndex: number
    show: boolean
    tabList: any
    queryData: any
  } = {
    appointList: [],
    show: false,
    queryData: {
      reserveDateEnd: '',
      reserveDate: '',
      reserveStatus: '',
      audit_type: '',
      goods_name: '',
      k: '',
      allShow: 0,
      pageSize: 10,
      p: 1
    },
    tabList: [{title: '全部', value: 'all', index: 0}, {title: '待预约', value: '3', index: 4}, {
      title: '待审核',
      value: '0',
      index: 1
    }, {title: '已成功', value: '1', index: 2}, {title: '已拒绝', value: '2', index: 3}],
    tabIndex: 0,
  }

  async componentDidShow() {
    vcmonitor(this);
  }

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    const appointList = await this.getData(this.state.queryData)
    this.setState({appointList})
  }

  page = 1

  async getData(queryData) {
    const appointList = await http.get<ReverseItem[]>(APPONINTMENT_MY, queryData)
    return appointList || []
  }

  onReachBottom() {
    this.page++
    const {queryData} = this.state
    queryData['p'] = this.page
    this.setState({queryData}, async () => {
      const appointList = await this.getData(this.state.queryData)
      const old = this.state.appointList
      this.setState({appointList: [...old, ...appointList]})
    })
  }

  async handlerTab(tabIndex, audit_type) {
    this.page = 1
    const {queryData} = this.state
    queryData['p'] = this.page
    queryData['audit_type'] = audit_type
    this.setState({tabIndex, queryData}, async () => {
      const appointList = await this.getData(queryData)
      this.setState({appointList})
    })
  }

  handleChange(field, val) {
    if (typeof val === 'object') {
      val = val.detail.value
    }
    const {queryData} = this.state
    queryData[field] = val
    this.setState({queryData})
  }

  onClose() {
    this.setState({show: false})
  }

  async handleForm(flag) {
    const {queryData} = this.state
    this.page = 1
    queryData['p'] = 1
    if (flag) {
      queryData['reserveDateEnd'] = ''
      queryData['reserveDate'] = ''
      queryData['goods_name'] = ''
      this.setState({queryData})
      return
    }
    this.onClose()
    const appointList = await this.getData(this.state.queryData)
    this.setState({appointList})
  }

  onCancel(item) {
    const that = this
    Taro.showModal({
      title: '提示',
      content: '您确定要取消吗?',
      cancelText: '取消',
      confirmText: '确定',
      success: async function (res) {
        const data = await http.HPost(ORDER_REFUND, {oid: item.orderId})
        if (data.isOk) {
          const appointList = await that.getData(that.state.queryData)
          that.setState({appointList})
          Taro.showToast({title: '操作成功！'})
        } else {
          Taro.showToast({title: data.msg, icon: "none"})
        }
      }
    })
  }

  render() {
    const {appointList, tabIndex, tabList, show, queryData} = this.state
    return (
      <View className='my-reverse appoint-list-root'>
        <GzhAuth />
        <View className='top-tab'>
          {tabList.map(item =>
            <View key={item.index} className={`tab-item ${tabIndex === item.index ? 'tab-item-active' : ''}`}
              onClick={this.handlerTab.bind(this, item.index, item.value)}
            >{item.title}
              <View className={`at-tabs_item_underline ${tabIndex === item.index ? 'underline-active' : ''}`} />
            </View>
          )}
        </View>
        <View className='tab-item-search-right' onClick={() => {
          this.setState({show: true})
        }}
        ><AtIcon size='16' value='icon icon-shaixuan-01' className='filter' /><Text
          className='filter-title'
        >筛选</Text></View>
        <View className='appoint-content appoint-content-my'>
          {appointList.length > 0 && appointList.map((item: any,  index) =>
            <View className='item' key={index}>
              <View className='title-box'>
                <View className='title-box-status'>{item.statusStr}</View>
                <View className='title'>
                  <View className={`${TARO_ENV}`}>{item.name}</View>
                  <View className='num'>x{item.num}</View>
                </View>
                <View className='line' />
                <View className='time'>预约时间：{item.add_date}</View>
                <View className='order-time'>预订时间：{item.dataRange ? item.dataRange : item.reserve_date}</View>
                {item.change_date_remark && <View className='order-time-change-date'>改期日期：<Text
                  className='change-date'
                >{item.change_date_remark.reserve_date}</Text></View>}
                <View className='detail-view'>
                  {!!item.is_allow_refund &&
                    <View className='detail-btn cancel' onClick={this.onCancel.bind(this, item)}>
                      <Text>取消</Text>
                    </View>
                  }
                  <View className='detail-btn' onClick={() => {
                    Taro.navigateTo({url: '/other/appointment/detail?itemId=' + item.uuid})
                  }}
                  >详情</View>
                </View>
              </View>
            </View>
          )}
          {appointList.length <= 0 &&
            <View style='text-align:center; font-size:14px; padding: 40px 0; color: #aaa;'>您还没有预约信息</View>}
        </View>
        <AtDrawer show={show} right mask onClose={this.onClose.bind(this)}>
          <View className='view-m-b'>
            <AtInput name='goods_name' title='商品名称' type='text' value={queryData.goods_name}
              onChange={this.handleChange.bind(this, 'goods_name')}
            />
          </View>
          <View className='view-m-b-reserve-date'>
            <Picker mode='date' onChange={this.handleChange.bind(this, 'reserveDate')}>
              <AtList>
                <AtListItem title='预订时间起' extraText={queryData.reserveDate} />
              </AtList>
            </Picker>
          </View>
          <View className='view-m-b view-m-b-reserve-date-end'>
            <Picker mode='date' onChange={this.handleChange.bind(this, 'reserveDateEnd')}>
              <AtList>
                <AtListItem title='预订时间止' extraText={queryData.reserveDateEnd} />
              </AtList>
            </Picker>
          </View>
          <View className='dialog-footer'>
            <View className='reset' onClick={this.handleForm.bind(this, true)}>重置</View>
            <View className='search' onClick={this.handleForm.bind(this, false)}>搜索</View>
          </View>
        </AtDrawer>
      </View>
    )
  }
}
